<?php
namespace PHPSpring\Core;

use PHPSpring\Application;
use PHPSpring\Utils\Scanner;

class RuntimeAnnotation {

  public static string $projectPath = '';
  public static string $cacheDir = '';

  public static string $cacheDirName = '.cache';
  public static string $annosFileName = 'annos.php';

  private static array $annotations;

  public static function init ($projectPath='') {
    if (!empty(self::$projectPath)) {
      return;
    }
    if (empty($projectPath)) {
      $projectPath = getcwd();
    }
    self::$projectPath = $projectPath;
    $cacheDir = $projectPath . DIRECTORY_SEPARATOR . self::$cacheDirName;
    if (!file_exists($cacheDir)) {
      mkdir($cacheDir, 0755, true);
    }
    self::$cacheDir = $cacheDir;
  }

  public static function getAnnotationFile () {
    return self::$cacheDir . DIRECTORY_SEPARATOR . self::$annosFileName;
  }

  public static function getAnnotations(string $className=null) {
    if(empty(self::$annotations)) {
      self::init();
      $annoFile = self::getAnnotationFile();
      if (!file_exists($annoFile)) {
        if (Application::config('app.debug')) {
          $appPath = Application::appPath();
          $appDir = basename($appPath);
          self::$annotations = Scanner::scan($appPath, null, ucfirst($appDir));
        } else {
          return array();
        }
      } else {
        self::$annotations = require($annoFile);
      }
    }
    if ($className != null) {
      $className = explode('\\', $className);
      $className = strtolower(array_pop($className));
      return self::$annotations[$className] ?? null;
    } else {
      return self::$annotations;
    }
  }

}
